 /*
  if/else 语句会根据我们关注的条件是否为真来执行代码，与之对应的，switch语句关注某个特殊的值
  并将其与一些了分支（case）进行匹配；
  switch value
  {
  case someValueToCompare:
    //做一些事情
  case someValueToCompare:
    //做一些事情
  default：
    //没有匹配的时候做的事情
  }
  */

import Cocoa

 var statusCode:Int = 404
 var errorString:String = ""
 
 switch statusCode
 {
    case 400:
        errorString = "Bad request"
    case 401:
        errorString = "Unauthorized"
    case 403:
        errorString = "Forbidden"
    case 404:
        errorString = "Not found"
    default:
        errorString = "None"
 }

 switch statusCode
 {
    case 400,401,402,403,404:
        errorString = "There was something wrong with the request."
        fallthrough //虽然这个分支匹配上了，但是还要执行下一个条件分支
    default:
        errorString += " Please review the request and try again."
 }

 //2.区间
 /*
  Swith 允许用一个值与一个特定区间的值做比价
  */

 switch statusCode
 {
    case 300...309:
        errorString = "Redirection,3xxx."
    case 400...409:
    errorString = "Client err,4xx."
    default:
        errorString = "UnKnown"
 }

 
 //3.值绑定
 errorString = "The request failed with the error:"
 switch statusCode
 {
    case 100,101:
        errorString += "Informational,\(statusCode)."
    case 204:
        errorString += "Successful but no content,204"
    case 300...307:
        errorString += "Redirection,\(statusCode)"
    
    case let unknownCode:
        errorString = "\(unknownCode) is not a known error code"
    //其实用标准的default就可以实现这个功能，这里只是展示swith有这样的语法。
 }

 
 //4.where子句
 switch statusCode {
 case 100,101:
    errorString += "Information,\(statusCode)"
 case let unknownCode where (unknownCode >= 200 && unknownCode < 300) || unknownCode > 505:
    errorString = "\(unknownCode) is not a known error code"
 default:
    errorString = "unexpected error encountered"
 }

 
 //5.元组和模式匹配
 /*
  什么是元组呢，举个例子，上面有了statusCode和errorString后，吧这两块信息拼接起来就很有用了。尽管两者逻辑相关，但是目前是存储在两个独立变量中的。
  元组（tuple）可以用来组合这两个变量。
  */
 switch statusCode {
 case 100,101:
    errorString += "Informational,\(statusCode)"
 case let unknownCode where (unknownCode >= 200 && unknownCode < 300) || unknownCode > 505:
    errorString = "\(unknownCode) is not a known error code"
 default:
    errorString = "unexpected error encountered"
 }
 //用一堆小括号创建元祖
 let error = (statusCode,errorString)
 //元祖的值可以用索引访问
 error.0
 error.1
 //给元祖的元素取名
 let error1 = (code:statusCode,error:errorString)
 error1.code
 error1.error
 
 //6.利用元组做模式匹配
 let firstErrorCode = 404
 let secondErrorCode = 200
 let errorCodes  = (firstErrorCode,secondErrorCode)
 switch errorCodes {
 case (404,404):
    print("NO items found.")
 case(_,404):
    print("first item not found")
 case(404,_):
    print("second item not found")
 default:
    print("all items found.")
 }

 
 //7.if case条件
 let age = 25
 switch age {
 case 18...35:
    print("Cool")
 default:
    break
 }
 //另外一种优雅的写法
 if case 18...35 = age ,age > 21 {
    print("Cool")
 }
 
